package com.dragon.concurrent.demo.demo;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class ThreadLifeCycleObServer implements LifeCycleListener {

    private final Object LOCK = new Object();

    public void concurrencyQuery(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        ids.stream()
                .forEach(id -> new Thread(new ObservableRunnable(this) {
                    @Override
                    public void run() {
                        notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                        System.out.println("query for the id:" + id);
                        try {
                            TimeUnit.SECONDS.sleep(5L);
                            notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
                        } catch (InterruptedException e) {
                            notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), null));
                        }
                    }
                }).start());
    }

    @Override
    public void onEvent(ObservableRunnable.RunnableEvent runnableEvent) {
        synchronized (LOCK) {
            System.out.println("the runnable [" + runnableEvent.getThread().getName() + "] data changed and state is:"
            + runnableEvent.getState());
            if (runnableEvent.getState() == ObservableRunnable.RunnableState.ERROR) {
                runnableEvent.getCause().getStackTrace();
            }
        }
    }
}
